package com.hjc.service.impl;

import com.hjc.entity.Result;
import com.hjc.entity.Role;
import com.hjc.entity.User;
import com.hjc.mapper.UserMapper;
import com.hjc.page.Page;
import com.hjc.service.UserService;
import com.hjc.utils.DigestUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public User queryUserByCode(String userCode) {
        return userMapper.findUserByCode(userCode);
    }

    @Override
    public Page queryUserByPage(Page page, User user) {
        Integer userRowCount = userMapper.findUserRowCount(user);
        List<User> userList = userMapper.findUserByPage(page, user);
        page.setTotalNum(userRowCount);
        page.setResultList(userList);
        return page;
    }

    @Override
    public Result saveUser(User user) {
        User oldUser = userMapper.findUserByCode(user.getUserCode());
        if(oldUser != null) {
            return Result.err(Result.CODE_ERR_BUSINESS,"该用户已存在！");
        }
        String pwd = DigestUtil.hmacSign(user.getUserPwd());
        user.setUserPwd(pwd);
        int flag = userMapper.insertUser(user);
        if(flag > 0) {
            return Result.ok("新增用户成功！");
        }

        return Result.err(Result.CODE_ERR_BUSINESS,"新增用户失败！");
    }

    @Override
    public Result setUserState(User user) {
        String userState = user.getUserState();
        String msg = userState.equals("1")  ? "启用" : "禁用";
        int flag = userMapper.updateUserState(user.getUserId(), user.getUserState());
        if(flag > 0) {
            return Result.ok(msg + "成功！");
        }
        return Result.err(Result.CODE_ERR_BUSINESS,msg + "失败！");
    }

    @Override
    public Result queryRoleByUserId(Integer userId) {
        List<Role> roleList = userMapper.findRoleByUserId(userId);
        return Result.ok(roleList);
    }

    @Override
    public Result removeUserByUserId(List<Integer> userIdList) {
        int flag = userMapper.setUserDelete(userIdList);
        if(flag > 0) {
            return Result.ok("删除成功!");
        }
        return Result.err(Result.CODE_ERR_BUSINESS,"删除失败！");
    }

    @Override
    public Result setUserNameByUserId(User user) {
        int flag = userMapper.updateUserNameByUserId(user);
        if (flag > 0) {
            return Result.ok("更新用户信息成功！");
        }
        return Result.err(Result.CODE_ERR_BUSINESS,"更新失败！");
    }

    @Override
    public Result setPwdByUserId(Integer userId) {
        String password = DigestUtil.hmacSign("123456");
        int flag = userMapper.setPwdByUserId(userId, password);
        if (flag > 0) {
            return Result.ok("重置密码成功！");
        }
        return Result.err(Result.CODE_ERR_BUSINESS,"重置密码失败！");
    }


}
